<?php

namespace app\publics\controller\api;

use app\ApiController;
use think\Db;

use app\mainadmin\model\PaymentModel;
use app\mainadmin\model\SmsTplModel;
use think\facade\Log;

/*------------------------------------------------------ */
//-- 支付相关API
/*------------------------------------------------------ */

class Payjxc extends ApiController
{

    public $payment; //  具体的支付类
    public $pay_code; //  具体的支付code
    /*------------------------------------------------------ */
    //-- 优先执行
    /*------------------------------------------------------ */
    public function initialize()
    {
        parent::initialize();
        $this->Model = new PaymentModel();
    }

    public function beanPay()
    {
        $payment = (new PaymentModel)->where('pay_code', 'integral')->find();
        if (empty($payment) || $payment['status'] != 1) {
            return $this->error('支付方式错误.');
        }
        $_from = input('_from', 'shop', 'trim');
        $order_id = input('order_id/d'); // 订单id
        return $this->publicBalancePay($payment, $order_id, 'integral_money');
    }
    /*------------------------------------------------------ */
    //-- 支付处理
    /*------------------------------------------------------ */
    public function getCode()
    {

        Log::info("测试config参数测试111=");
        // 获取支付方式
        $pay_code = input('pay_code');
        unset($_GET['pay_code']); // 用完之后删除, 以免进入签名判断里面去 导致错误
        define('SITE_URL', config('config.host_path'));
        // 导入具体的支付类文件
        $code = str_replace('/', '\\', "/payment/{$pay_code}/{$pay_code}");
        $this->payment = new $code();
        $order_id = input('order_id/d'); // 订单id
        $_from = input('_from', '', 'trim'); // 来源
        $payType = input('payType', '', 'trim'); // 类型
        if ($_from == 'shop') { //
            if ($payType == 'order') { //订单
                $OrderModel = new \app\jxcshop\model\OrderModel();
                $order = $OrderModel->where("order_id", $order_id)->find();
                if ($order['pay_status'] == 1) {
                    return $this->error('此订单，已完成支付.');
                }
                if ($order['order_status'] == 2) {
                    return $this->error('此订单，已取消不能执行支付.');
                }
                $config['body'] = $OrderModel->getPayBody($order_id);
            } elseif ($payType == 'recharge') { //充值

            } else {
                return $this->error('未知操作.');
            }
        } elseif ($_from == 'channel') {
            if ($payType == 'order') { //订单
                $OrderModel = new \app\channel\model\OrderModel();
                $order = $OrderModel->where("order_id", $order_id)->find();
                if ($order['pay_status'] == 1) {
                    return $this->error('此订单，已完成支付.');
                }
                if ($order['order_status'] == 2) {
                    return $this->error('此订单，已取消不能执行支付.');
                }
            } elseif ($payType == 'recharge') { //充值
                $RechargeLogModel = new \app\channel\model\RechargeLogModel();
                $order = $RechargeLogModel->where("order_id", $order_id)->find();
                if ($order['status'] == 9) {
                    return $this->error('已完成支付.');
                }
            } else {
                return $this->error('未知操作.');
            }
        }

        if ($order['order_type'] == 4) {
            if ($this->userInfo['role_id'] !== 0 && $this->userInfo['role_id'] !== 3) {
                return $this->error('仅限粉丝和会员身份可以购买.');
            }
        } elseif ($order['order_type'] == 5) {
            if ($this->userInfo['role_id'] <= 0) {
                return $this->error('本月您已领取过商品免费领商品.');
            }
            $start = mktime(0, 0, 0, date('m'), 1, date('Y')); //这个月的开始日期
            $end = mktime(23, 59, 59, date('m') + 1, 0, date('Y')); //这个月的结束日期
            $count = $OrderModel->where([
                ['order_type', '=', 5],
                ['user_id', '=', $this->userInfo['user_id']],
                ['order_status', '=', 1],
                ['add_time', 'between', [$start, $end]]
            ])
                ->count();
            if ($count > 0) {
                return $this->error('本月您已领取过商品免费领商品.');
            }
        }


        $config = parseUrlParam($this->pay_code); // 类似于 pay_code=alipay&bank_code=CCB-DEBIT 参数
        Log::info("测试config参数测试=" . json_encode($config));
//        dump("config");
//        dump($config);
//        die();
        $payment = (new PaymentModel)->where('pay_code', $pay_code)->find();
        if (empty($payment)) {
            return $this->error('相关支付方式不存在.');
        }
        if ($payment['status'] == 0) {
            return $this->error('相关支付方式已停用.');
        }
        $payType = 1;
        if ($pay_code == 'weixin') {
            $openid = input('openid', '', 'trim');
            $trade_type = input('trade_type', '', 'trim');
//            if ($trade_type == 'js') {
            //微信JS支付
            $payConfig = $this->payment->getJSAPI($order, $openid);
            if (is_array($payConfig) == false) {
                $payConfig = json_decode($payConfig, true);
            }
            if ($payConfig['return_code'] == 'FAIL') {
                return $this->error($payConfig['return_msg']);
            } //            }
            else if ($trade_type == 'h5') {
                $config['body'] = '微信支付';
                //微信H5支付
                $h5PayRes = $this->payment->get_H5code($order, $config);
                if (is_array($h5PayRes) == false) {
                    $h5PayRes = json_decode($h5PayRes, true);
                }
                if ($h5PayRes['result']['return_code'] == 'FAIL') {
                    return $this->error($h5PayRes['result']['return_msg']);
                }
                $payConfig = $h5PayRes['result'];
            }
        } elseif ($pay_code == 'appWeixinPay') {
            $payConfig = $this->payment->getAppPay($order, $config);
            $payConfig = json_decode($payConfig, true);
            if ($payConfig['result_code'] == 'FAIL') {
                return $this->error($payConfig['err_code_des']);
            }
        } else {
            //其他支付（支付宝、银联...）
            $payConfig = $this->payment->get_code($order, $config);
        }
        if ($payConfig == false) {
            return $this->error('处理支付失败111.' . $_SERVER['SERVER_NAME']);
        }

        $data['payConfig'] = $payConfig;
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 积分支付
    /*------------------------------------------------------ */
    public function balancePay()
    {
        $payment = (new PaymentModel)->where('pay_code', 'balance')->find();
        if (empty($payment) || $payment['status'] != 1) {
            return $this->error('支付方式错误.');
        }
        $_from = input('_from', 'shop', 'trim');
        $order_id = input('order_id/d'); // 订单id
        if ($_from == 'channel') {
            return $this->channelBalancePay($payment, $order_id);
        } else {
            return $this->publicBalancePay($payment, $order_id);
        }

    }
    /*------------------------------------------------------ */
    //-- 货款支付
    /*------------------------------------------------------ */
    public function goodsMoneyPay()
    {
        $order_id = input('order_id/d'); // 订单id
        $OrderModel = new \app\channel\model\OrderModel();
        $order = $OrderModel->where("order_id", $order_id)->find();
        if ($order['pay_status'] == 1) {
            return $this->error('此订单，已完成支付.');
        }
        if ($order['order_status'] == 2) {
            return $this->error('此订单，已取消不能执行支付.');
        }
        if ($order['user_id'] != $this->userInfo['user_id']) {
            return $this->error('此订单你无权操作.');
        }
        $WalletModel = new \app\channel\model\WalletModel();
        $account = $WalletModel->getWalletInfo($this->userInfo['user_id'], false);//获取代理会员帐户信息
        if ($order['order_amount'] > $account['goods_money']) {
            return $this->error('货款积分不足，请使用其它支付方式.');
        }
        Db::startTrans();//启动事务
        $changedata['by_id'] = $order_id;
        $changedata['change_desc'] = '订单支付';
        $changedata['change_type'] = 2;
        $changedata['goods_money'] = $order['order_amount'] * -1;
        $changedata['goods_money_outlay_total'] = $order['order_amount'];
        $res = $WalletModel->change($changedata, $this->userInfo['user_id'], false);
        if ($res !== true) {
            Db::rollback();//回滚事务
            return $this->error('更新帐户信息失败.');
        }
        //完成支付
        $upArr['order_id'] = $order_id;
        $upArr['pay_code'] = 'goodsMoney';
        $upArr['pay_id'] = 99;
        $upArr['pay_name'] = '货款支付';
        $upArr['money_paid'] = $order['order_amount'];
        $res = $OrderModel->updatePay($upArr, '货款支付成功.');
        if ($res !== true) {
            Db::rollback();// 回滚事务
            return $this->error($res);
        }
        Db::commit();// 提交事务
        return $this->success();
    }
    /*------------------------------------------------------ */
    //-- 升级货款支付
    /*------------------------------------------------------ */
    public function uplevelGoodsMoneyPay()
    {
        $order_id = input('order_id/d'); // 订单id
        $OrderModel = new \app\jxcshop\model\OrderModel();
        $order = $OrderModel->where("order_id", $order_id)->find();
        if ($order['pay_status'] == 1) {
            return $this->error('此订单，已完成支付.');
        }
        if ($order['order_status'] == 2) {
            return $this->error('此订单，已取消不能执行支付.');
        }
        if ($order['user_id'] != $this->userInfo['user_id']) {
            return $this->error('此订单你无权操作.');
        }
        $WalletModel = new \app\channel\model\WalletModel();
        $account = $WalletModel->getWalletInfo($this->userInfo['user_id'], false);//获取代理会员帐户信息
        if ($order['order_amount'] > $account['uplevel_goods_money']) {
            return $this->error('升级货款积分不足，请使用其它支付方式.');
        }
        Db::startTrans();//启动事务
        $changedata['by_id'] = $order_id;
        $changedata['change_desc'] = '订单支付';
        $changedata['change_type'] = 2;
        $changedata['uplevel_goods_money'] = $order['order_amount'] * -1;
        $res = $WalletModel->change($changedata, $this->userInfo['user_id'], false);
        if ($res !== true) {
            Db::rollback();//回滚事务
            return $this->error('更新帐户信息失败.');
        }
        //完成支付
        $upArr['order_id'] = $order_id;
        $upArr['pay_code'] = 'uplevelGoodsMoney';
        $upArr['pay_id'] = 98;
        $upArr['pay_name'] = '升级货款支付';
        $upArr['money_paid'] = $order['order_amount'];
        $res = $OrderModel->updatePay($upArr, '升级货款支付成功.');
        if ($res !== true) {
            Db::rollback();// 回滚事务
            return $this->error($res);
        }
        Db::commit();// 提交事务
        return $this->success();
    }
    /*------------------------------------------------------ */
    //-- 代理积分支付
    /*------------------------------------------------------ */
    public function channelBalancePay($payment, $order_id)
    {
        $OrderModel = new \app\channel\model\OrderModel();
        $order = $OrderModel->where("order_id", $order_id)->find();
        if ($order['pay_status'] == 1) {
            return $this->error('此订单，已完成支付.');
        }
        if ($order['order_status'] == 2) {
            return $this->error('此订单，已取消不能执行支付.');
        }
        if ($order['user_id'] != $this->userInfo['user_id']) {
            return $this->error('此订单你无权操作.');
        }
        $WalletModel = new \app\channel\model\WalletModel();
        $account = $WalletModel->getWalletInfo($this->userInfo['user_id'], false);//获取代理会员帐户信息
        if ($order['order_amount'] > $account['balance_money']) {
            return $this->error('积分不足，请使用其它支付方式.');
        }
        Db::startTrans();//启动事务
        $changedata['by_id'] = $order_id;
        $changedata['change_desc'] = '订单支付';
        $changedata['change_type'] = 2;
        $changedata['balance_money'] = $order['order_amount'] * -1;
        $res = $WalletModel->change($changedata, $this->userInfo['user_id'], false);
        if ($res !== true) {
            Db::rollback();//回滚事务
            return $this->error('更新帐户信息失败.');
        }
        //积分完成支付
        $upArr['order_id'] = $order_id;
        $upArr['pay_code'] = $payment['pay_code'];
        $upArr['pay_id'] = $payment['pay_id'];
        $upArr['pay_name'] = $payment['pay_name'];
        $upArr['money_paid'] = $order['order_amount'];
        $res = $OrderModel->updatePay($upArr, '积分支付成功.');
        if ($res !== true) {
            Db::rollback();// 回滚事务
            return $this->error($res);
        }
        Db::commit();// 提交事务
        return $this->success();
    }

    /*------------------------------------------------------ */
    //-- 公用积分支付，一般商城使用
    /*------------------------------------------------------ */
    public function publicBalancePay($payment, $order_id, $type = 'balance_money')
    {
        $OrderModel = new \app\jxcshop\model\OrderModel();
        $order = $OrderModel->where("order_id", $order_id)->find();
        if ($order['order_type'] == 4) {

            if ($this->userInfo['role_id'] !== 0 && $this->userInfo['role_id'] !== 3) {
                return $this->error('仅限粉丝身份可以购买.');
            }
        } elseif ($order['order_type'] == 5) {
            if ($this->userInfo['role_id'] <= 0) {
                return $this->error('本月您已领取过商品免费领商品.');
            }
            $start = mktime(0, 0, 0, date('m'), 1, date('Y')); //这个月的开始日期
            $end = mktime(23, 59, 59, date('m') + 1, 0, date('Y')); //这个月的结束日期
            $count = $OrderModel->where([
                ['order_type', '=', 5],
                ['user_id', '=', $this->userInfo['user_id']],
                ['order_status', '=', 1],
                ['add_time', 'between', [$start, $end]]
            ])
                ->count();
            if ($count > 0) {
                return $this->error('本月您已领取过商品免费领商品.');
            }
        }
        if ($order['pay_status'] == 1) {
            return $this->error('此订单，已完成支付.');
        }
        if ($order['order_status'] == 2) {
            return $this->error('此订单，已取消不能执行支付.');
        }
        if ($order['user_id'] != $this->userInfo['user_id']) {
            return $this->error('此订单你无权操作.');
        }

        if ($order['order_amount'] > $this->userInfo['account'][$type]) {
            return $this->error('积分不足，请使用其它支付方式.');
        }
        Db::startTrans();//启动事务
        $upData['money_paid'] = $order['order_amount'];
        $upData['pay_time'] = time();
        $changedata['change_desc'] = '积分支付';
        $changedata['change_type'] = 3;
        $changedata['by_id'] = $order_id;
        $changedata[$type] = $order['order_amount'] * -1;
        $res = (new \app\member\model\AccountModel)->change($changedata, $order['user_id'], false);
        if ($res !== true) {
            Db::rollback();// 回滚事务
            return $this->error('支付失败，扣减积分失败.');
        }
        $balance_money = (new \app\member\model\AccountModel)->where('user_id', $order['user_id'])->value($type);
        if ($balance_money < 0) {
            Db::rollback();// 回滚事务
            return $this->error('支付失败，扣减积分失败.');
        }
        //积分完成支付
        $upArr['order_id'] = $order_id;
        $upArr['pay_code'] = $payment['pay_code'];
        $upArr['pay_id'] = $payment['pay_id'];
        $upArr['pay_name'] = $payment['pay_name'];
        $upArr['money_paid'] = $order['order_amount'];
        $res = $OrderModel->updatePay($upArr, '积分支付成功.');
        if ($res !== true) {
            Db::rollback();// 回滚事务
            return $this->error($res);
        }
        Db::commit();// 提交事务
        return $this->success();
    }

    /**
     * [judgePay 判断是否支付成功]
     */
    public function judgePay()
    {
        $order_id = input('order_id', 0, 'intval');
        $order = \app\jxcshop\model\OrderModel::where("order_id", $order_id)->find();
        if (empty($order)) return $this->error(['订单不存在.', -2]);
        if ($order['pay_status'] == 1 && $order['pay_time'] > 0) {
            //发送验证码
            $this->sendAdminCode($order['order_sn']);
            return $this->success();
        }
        $this->error(['支付失败.', -1]);
    }
    /*------------------------------------------------------ */
    //-- 发送验证短信
    /*------------------------------------------------------ */
    public function sendAdminCode($order_sn)
    {

        $sms_fun = settings('sms_fun');
        $sms_tpl = SmsTplModel::getRows();
        $smsTpl = $sms_tpl["to_send_admin"];
        $mobile = db("main_admin_user")->where("user_id=10002")->value("moblie");
        $fun = str_replace('/', '\\', '/sms/' . $sms_fun['function']);
        //生成随机码
        $Class = new $fun($sms_fun['function_val']);
        $Class->send($mobile, $smsTpl['sms_tpl_code'], ['order_sn' => $order_sn]);
        return true;
    }


}
